const fs = require("mz/fs") 
const  mime  = require('mime') 
const path =  require('path') 

function  template(staticFileName, dir){
  return async (ctx, next) => {
    const filePath = ctx.request.path;
    if(filePath.startsWith(staticFileName)){
      const  fullPath = path.join(dir, filePath.substring(staticFileName.length))
      if(await fs.exists(fullPath)){
        ctx.response.type = mime.lookup(fullPath)
        ctx.response.body = await fs.readFile(fullPath)
      }else{
        ctx.response.status = 400
      }
    }else{
      await next()
    } 
  }
}

module.exports = template